import os
import re
import subprocess
import csv_to_docx
from docx import Document
from docx.oxml.ns import qn
from docx.oxml import parse_xml
from PIL import Image
import io
import xml.etree.ElementTree as ET


def docx_to_markdown(docx_path, output_md_path, media_dir="media", tables_dir="tables"):
    """
    将Word文档转换为Markdown格式，保留所有结构、表格和图片
    表格将保存为CSV文件，并在原位置添加引用链接
    """
    # 创建媒体文件夹和表格文件夹
    os.makedirs(media_dir, exist_ok=True)
    os.makedirs(tables_dir, exist_ok=True)

    # 加载Word文档
    doc = Document(docx_path)

    # 初始化Markdown内容
    md_content = []
    image_count = 0
    table_count = 0  # 表格计数器

    # 遍历文档中的所有元素（按原始顺序）
    for element in doc.element.body:
        # 处理段落
        if element.tag.endswith('p'):
            # 找到对应的段落对象
            for para in doc.paragraphs:
                if para._element is element:
                    # 处理段落文本
                    if para.text.strip():
                        md_content.append(process_paragraph(para))

                    # 处理段落中的图片
                    images_md = process_images_in_paragraph(para, media_dir, image_count)
                    if images_md:
                        md_content.append(images_md)
                        image_count += images_md.count("![图片描述]")
                    break

        # 处理表格
        elif element.tag.endswith('tbl'):
            # 找到对应的表格对象
            for table in doc.tables:
                if table._element is element:
                    table_count += 1
                    # 生成CSV文件名
                    csv_filename = f"table_{table_count}.csv"
                    csv_path = os.path.join(tables_dir, csv_filename)

                    # 保存表格为CSV
                    save_table_as_csv(table, csv_path)

                    # 在Markdown中添加CSV文件引用
                    relative_csv_path = os.path.relpath(csv_path, start=os.path.dirname(output_md_path))
                    md_content.append(f"[表格已导出为CSV文件]({relative_csv_path})")
                    break

    # 保存Markdown文件
    with open(output_md_path, 'w', encoding='utf-8') as md_file:
        md_file.write("\n\n".join([c for c in md_content if c]))

    print(f"Markdown文件已保存至: {output_md_path}")
    print(f"图片已保存至: {media_dir}")
    print(f"表格已保存为CSV文件至: {tables_dir}")
    print(f"共转换 {table_count} 个表格")


def save_table_as_csv(table, csv_path):
    """
    将Word表格保存为CSV文件
    """
    with open(csv_path, 'w', encoding='utf-8', newline='') as csvfile:
        writer = csv.writer(csvfile)

        for row in table.rows:
            # 获取行数据
            row_data = []
            for cell in row.cells:
                # 清理单元格文本（移除多余空格和换行）
                cell_text = cell.text.strip().replace('\n', ' ')
                row_data.append(cell_text)

            # 写入CSV
            writer.writerow(row_data)


def process_paragraph(para):
    """
    处理段落：转换标题、列表和普通文本
    """
    text = para.text.strip()
    if not text:
        return ""

    # 处理标题
    if para.style.name.startswith('Heading'):
        level = int(para.style.name.split()[-1])
        return f"{'#' * level} {text}"

    # 处理加粗文本
    text = re.sub(r'\*\*(.*?)\*\*', r'**\1**', text)

    # 处理列表
    if para.style.name == 'List Paragraph' or para.style.name.startswith('List'):
        return f"- {text}"

    # 处理普通文本中的换行
    text = text.replace('\n', '  \n')  # Markdown中的两个空格表示换行

    return text


def process_images_in_paragraph(para, media_dir, img_index):
    """
    处理段落中的图片
    """
    md_images = []

    for run in para.runs:
        # 检查运行中是否包含图片
        drawing = run._element.find('.//' + qn('w:drawing'))
        if drawing is not None:
            # 查找图片元素
            blip = drawing.find('.//' + qn('a:blip'))
            if blip is not None:
                try:
                    # 获取图片ID
                    embed_attr = qn('r:embed')
                    image_id = blip.get(embed_attr)

                    if image_id:
                        # 获取图片数据
                        image_part = run.part.related_parts[image_id]
                        image_bytes = image_part.blob

                        # 生成图片文件名
                        try:
                            img = Image.open(io.BytesIO(image_bytes))
                            image_ext = img.format.lower()
                        except:
                            image_ext = "png"  # 默认使用PNG格式

                        image_name = f"image{img_index}.{image_ext}"
                        image_path = os.path.join(media_dir, image_name)

                        # 保存图片
                        with open(image_path, 'wb') as img_file:
                            img_file.write(image_bytes)

                        # 添加Markdown图片引用
                        md_images.append(f"![图片描述]({image_path})")
                        img_index += 1  # 递增图片索引
                except Exception as e:
                    print(f"图片处理错误: {str(e)}")
                    md_images.append("[图片处理错误]")

    return "\n".join(md_images)


def enhance_markdown_with_pandoc(input_md, output_md):
    """
    使用pandoc增强Markdown格式（可选）
    """
    try:
        subprocess.run([
            'pandoc', '-s', input_md,
            '-t', 'markdown_strict+pipe_tables',
            '-o', output_md
        ], check=True)
        print(f"使用pandoc优化后的Markdown已保存至: {output_md}")
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("未找到pandoc，使用基本转换结果")

def docx_to_docx():
    # 配置路径
    docx_file = "D:\\hbyt\\AI智能投标\\markdown_output\\激励及绩效管理_v1.0_2201.docx"
    output_md = "D:\\hbyt\\AI智能投标\\markdown_output\\markdown_output1.md"
    enhanced_md = "D:\\hbyt\\AI智能投标\\markdown_output\\enhanced.md"
    media_folder = "D:\\hbyt\\AI智能投标\\markdown_output\\media"
    tables_folder = "D:\\hbyt\\AI智能投标\\markdown_output\\tables"

    # 确保输出目录存在
    os.makedirs(os.path.dirname(output_md), exist_ok=True)
    os.makedirs(media_folder, exist_ok=True)
    os.makedirs(tables_folder, exist_ok=True)

    # 执行转换
    docx_to_markdown(docx_file, output_md, media_folder, tables_folder)
    # 使用pandoc增强格式（可选）
    enhance_markdown_with_pandoc(output_md, enhanced_md)
